package com.sec.typhoondatapush.service.task;

import com.sec.typhoondatapush.entity.SinaStock;
import com.sec.typhoondatapush.repository.SinaStockRepository;
import com.sec.typhoondatapush.util.GetJson;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;


/**
 * 定时任务的服务
 *
 * @author zhuwq
 * @version V1.0
 * @date :Create in  2018/7/30- 15:11
 */
@Service
@Slf4j
public class ScheduleTask {

    @Autowired
    private SinaStockRepository sinaStockRepository;

    public void task1() {
        LocalDateTime time = LocalDateTime.now();
        log.warn("task1!:当前时间=" + time.getHour() + "时" + time.getMinute() + "分" + time.getSecond() + "秒");
        //url 生成
        String url = "https://gupiao.baidu.com/api/stocks/stocktimeline?from=pc&os_ver=1&cuid=xxx&vv=100&format=json&stock_code=sh600358&timestamp=" + System.currentTimeMillis();
        //访问获得json数据
        JSONObject jsonObject = new GetJson().getHttpJson(url, 1);
        JSONArray timeLines = jsonObject.getJSONArray("timeLine");
        for (Object timeLine : timeLines) {
            SinaStock stock = new SinaStock();
            stock.setDate(Integer.parseInt(((JSONObject) timeLine).get("date").toString()));
            stock.setVolume(Integer.parseInt(((JSONObject) timeLine).get("volume").toString()));
            stock.setAmount(Integer.parseInt(((JSONObject) timeLine).get("amount").toString()));
            stock.setPreClose(new BigDecimal(((JSONObject) timeLine).get("preClose").toString()));
            stock.setPrice(new BigDecimal(((JSONObject) timeLine).get("price").toString()));
            stock.setAvgPrice(new BigDecimal(((JSONObject) timeLine).get("avgPrice").toString()));
            stock.setNetChangeRatio(new BigDecimal(((JSONObject) timeLine).get("netChangeRatio").toString()));
            stock.setTime(Long.parseLong(((JSONObject) timeLine).get("time").toString()));
            stock.setCcl(Integer.parseInt(((JSONObject) timeLine).get("ccl").toString()));
            sinaStockRepository.save(stock);
//            Document document = Document.parse(timeLine.toString());
//            log.info(document.toString());
        }
//        log.info(timeLines.toString());
//        Document document = Document.parse(stock.toString());

    }

    public void task2() {
        LocalDateTime time = LocalDateTime.now();
        log.warn("task2:当前时间=" + time.getHour() + "时" + time.getMinute() + "分" + time.getSecond() + "秒");
    }

}
